/**
	This file is part of MemoryTrace.

	MemoryTrace is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

        Contributed by Ameziane NAIT ABDELAZIZ.
        
	MemoryTrace is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with MemoryTrace.  If not, see <http://www.gnu.org/licenses/>.
**/



#include "XmlLogger.hpp"
#include "back_trace.h"
#include "alloc_stats.h"
#include <unistd.h>//read
#include <string.h>//memcpy
#include <sys/types.h>//fd
#include <fcntl.h>  //open

#include <sys/stat.h>
#include <errno.h>

#include "alloc_event_t.h"


using namespace std;

#define MESSAGE "Le postraitement xml se trouvera dans "


void XmlLogger::openFile()
{
  sprintf(path,"memoryTraceProfile.%s.xml",this->bin.c_str());
  printf("%s %s\n",MESSAGE,path);
  
  out = fopen(path, "w+");
  assert(out!=NULL);
  
  /*ouverture du document xml*/
  fprintf(out,"<%s %s='%d' %s='%d' %s='%s'>\n",ROOT,PID,getpid(),PPID,getppid(),EXE,this->bin.c_str());
}

void XmlLogger::startMalloc(void* addr,size_t size,
				   unsigned int index,
				   int total_memory)
{
  /*Attention printf, fprint font de l'allocation dynamique*/  
  fprintf(out," <malloc v='%u' ret='%p' id='%d' tm='%d'>\n",(unsigned int)size,addr,index,total_memory); 
  
}

void XmlLogger::startCalloc(void* addr,
				   size_t nmemb,
				   size_t size,
				   int compteur_calloc,
				   unsigned int memory_allocation)
{ 

  fprintf(out, " <calloc v='%d' n='%u' ret='%p' id='%d' tm='%d'>\n",
	  (unsigned int)nmemb,
	  (unsigned int)size,
	  addr,
	  compteur_calloc,
	  memory_allocation);
}
  
void XmlLogger::startRealloc(void*  v,void*  ret,size_t n,int id,size_t tm){
 fprintf(out, " <realloc v='%p' n='%d' ret='%p' id='%d' tm='%d'>\n",v,(int)n,ret,id,(int)tm);
}

void XmlLogger::startFree(void* addr,unsigned nbfree){
  fprintf(out, " <free v='%p' id='%d'>\n", addr,nbfree);
}


void XmlLogger::endElement(const char *type){
  fprintf(out,"</%s>\n",type);
}



#define BUFFSIZE    100*EVENT_SIZE


void XmlLogger::finalizeLog(alloc_stats & stats){
 
  /*On ecrit le rapport des allocations*/
  fprintf(out,"\n<report>\n"); 
  fprintf(out," <mallocs  v='%d'/>\n",        stats.compteur_malloc); 
  fprintf(out," <callocs  v='%d'/>\n",        stats.compteur_calloc); 
  fprintf(out," <reallocs v='%d'/>\n",        stats.compteur_realloc); 
  fprintf(out," <total    v='%d octets'/>\n", (int)stats.memory_allocation);
  fprintf(out," <frees    v='%d'/>\n",        stats.compteur_free);
  fprintf(out,"</report>\n");
  
  /*On ferme le document XML*/
  fprintf(out,"</%s>\n",ROOT);	
}
